import router from '@/router/index'
import { asyncRoutes } from '@/router/asyncRoutes'
export function hasPermission(route, menus) {
  if (!route.name) return true

  const check = (menus) => {
    for (const menu of menus) {
      if (menu.name === route.name) return true
      if (menu.children && check(menu.children)) return true
    }
    return false
  }
  return check(menus)
}

export function filterAsyncRoutes(routes, menus) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(tmp, menus)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus)
      }
      res.push(tmp)
    }
  })
  console.log("res:",res)
  return res
}

export function setupDynamicRoutes(userMenus) {
  const accessRoutes = filterAsyncRoutes(asyncRoutes, userMenus)

  // 判断是否包含首页菜单，如果有则跳转到首页
  const hasIndexMenu = userMenus.some(menu => menu.title === '首页')
  
  // 动态添加路由
  accessRoutes.forEach(route => {
    router.addRoute(route)
  })
  resolve() // 挂载完再跳转
}
